<template>
	<h1>Rgeist</h1>
	<van-form @submit="onSubmit">
	  <van-cell-group inset>
	    <van-field
	      v-model="username"
	      name="username"
	      label="用户名"
	      placeholder="用户名"
	      :rules="[
			  { required: true, message: '请填写用户名' },
			  
			  ]"
	    />
	    <van-field
	      v-model="password"
	      type="password"
	      name="password"
	      label="密码"
	      placeholder="密码"
	      :rules="[{ required: true, message: '请填写密码' }]"
	    />
		<van-field
		  v-model="re_password"
		  type="password"
		  name="re_password"
		  label="密码"
		  placeholder="密码"
		  :rules="[
			  { required: true, message: '请确认密码' },
			  { validator: checkRePassword, message: '两次密码不一致'}
			]"
		/>
	  </van-cell-group>
	  <div style="margin: 16px;">
	    <van-button round block type="primary" native-type="submit">
	      提交
	    </van-button>
	  </div>
	</van-form>
</template>

<script setup lang="ts">
	import {ref} from 'vue'
	import {checkUsername, createUser} from '@/api/user'
	import { Toast } from 'vant';
	import router from '@/router'
	import 'vant/es/toast/style';
	
	const username = ref("")
	const password = ref("")
	const re_password = ref("")
	
	
	function onSubmit(data){
		console.log("Onsubmit...")
		// 调用注册接口
		// 1. api/user.ts => 定义请求api函数
		// 2. 在onSubmit调用请求api函数  Toast提示，成功、失败
		// var data = {
		// 	"username":username.value,
		// 	"password":password.value,
		// 	"re_password":re_password.value
		// }
		// res形式参数: response =>
		console.log(data)
		createUser(data)
		.then(res=>{
			console.log(res)
			if(res.code != 0){
				Toast.fail('失败文案');
			}else{
				Toast.success('成功文案');
				router.push({
					name:"login",
					query: {date:new Date().getTime()}
				})
			}
		})
		.catch(err=>{
			console.log(err)
		})
	}
	
	function checkUserRepete(name){
		console.log("检查用户名是否重名")
		// return false
		// return `${username.value}已经被注册`
		// return `${name}已经被注册`
		var parmas = {"username":name}
		var result = checkUsername(parmas)
		// 上面的内容执行成功
		.then(res => {
			console.log("api result", res)
			if(res.code != 0){
				return false
			}
			return true
		})
		// 上面checkUsername+then执行出错
		.catch(err => {
			console.log("error")
			return `出错了:${err}`
		})
		return result
	}
	
	function checkRePassword(){
		if(password.value != re_password.value){
			return false
		}
		return true
	}
	
	// 请求api -> axios -> 请求 url => /check/username
	// 将基础url放到配置文件中 => https://mock.presstime.cn/mock/635364243ea0490082820ad1/example/
	// /api/check/username => https://xxxxxxxxx/example/check/username
	// yarn dev => 开发环境development => 加载.env.development
	// 

</script>

<style>
</style>